import { useEffect, useState } from "react";
import { BaseDirectory, exists, readTextFile, writeTextFile } from '@tauri-apps/api/fs';
import { Button, Checkbox, Drawer, Form, Input, Modal } from 'antd';
import "./App.css";
import { DeleteOutlined, EditOutlined, PlusCircleOutlined } from "@ant-design/icons";
import "antd/dist/antd.css";
import Table, { ColumnsType } from "antd/lib/table";

interface PasswordItem { 
  id: string,
  name: string,
  url?: string,
  userName: string,
  password?: string,
  encrypt: boolean
}

interface PasswordCategory {
  id: string,
  name: string,
  datas: Array<PasswordItem>
}

interface PasswordMetaData {
  appName: string,
  version?: string,
  author?: string,
  createTime?: Date,
  updateTime?: Date,
  categorys: Array<PasswordCategory>,
}

const configFilePath = "Software/password-security/password-metadata.json";
const defaultConfig: PasswordMetaData = {
  appName: "Password-Security",
  version: "v1.0.0",
  author: "kuzank",
  categorys: [
    {
      id: "" + new Date().getTime(),
      name: "我的密码分组",
      datas: [
        {
          id: "" + new Date().getTime(),
          name: "QQ",
          userName: "754109648",
          encrypt: true
        },
        {
          id: "" + new Date().getTime(),
          name: "微信",
          userName: "kuzank",
          encrypt: true
        }
      ]
    }
  ]
}

function App() {
  const [passwordMetaData, setPasswordMetaData] = useState<PasswordMetaData>();
  const [passwordCategory, setPasswordCategory] = useState<PasswordCategory>();
  const [showEditPasswordCategory, setShowEditPasswordCategory] = useState(false);
  const [editPasswordCategoryData, setEditPasswordCategoryData] = useState<PasswordCategory>();
  const [isCreatePasswordItem, setIsCreatePasswordItem] = useState(false);
  const [showEditPasswordItem, setShowEditPasswordItem] = useState(false);
  const [editPasswordItemData, setEditPasswordItemData] = useState<PasswordItem>();
  const columns: ColumnsType<PasswordItem> = [
    {
      title: '系统',
      dataIndex: 'name',
      key: 'name',
      render: text => <a>{text}</a>,
    },
    {
      title: '账号',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '密码',
      dataIndex: 'password',
      key: 'password',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <div className="password-item-operation">
          <EditOutlined className="password-item-operation-item"  onClick={() => toggleEditPasswordItem(record)}/>
          <DeleteOutlined className="password-item-operation-item"  onClick={() => toggleDeletePasswordItem(record)} />
        </div>
      ),
    },
  ]

  useEffect(() => {
    loadPasswordMetaData();
  },[]);

  async function loadPasswordMetaData() {
    let fileExists = await exists(configFilePath, {dir: BaseDirectory.Home});
    if(fileExists) {
      readTextFile(configFilePath, {dir: BaseDirectory.Home})
      .then((res) => {
        let data = JSON.parse(res) as PasswordMetaData;
        if(data) {
          setPasswordMetaData(data);
          if(data.categorys && data.categorys.length > 0) {
            setPasswordCategory(data.categorys[0]);
          }
        } else {
          setPasswordMetaData(defaultConfig);
          setPasswordCategory(defaultConfig.categorys[0]);
        }
      })
      .catch((err) => {
        alert("读取配置文件失败！" + err);
      })
    } else {
      if(passwordMetaData) {
        setPasswordMetaData(passwordMetaData);
      } else {
        writeTextFile(configFilePath, JSON.stringify(defaultConfig), {dir: BaseDirectory.Home})
        .then((res) => {
          setPasswordMetaData(defaultConfig);
          setPasswordCategory(defaultConfig.categorys[0]);
        })
        .catch((err) => {
          alert("创建配置文件失败!" + err);
        });
      }
    }
  }

  function savePasswordMetaData() {
    writeTextFile(configFilePath, JSON.stringify(passwordMetaData), {dir: BaseDirectory.Home})
    .then((res) => {
      alert("操作成功!");
    })
    .catch((err) => {
      alert("操作失败!" + err);
    });
  }

  function toggleSelectPasswordCategory(category: PasswordCategory) {
    setPasswordCategory(category);
  }

  function toggleCreatePasswordCategory() {
    setEditPasswordCategoryData({
      id: "" + new Date().getTime(),
      name: "",
      datas: []
    });
    setShowEditPasswordCategory(true);
  }

  function toggleEditPasswordCategory(category: PasswordCategory) {
    setEditPasswordCategoryData(category);
    setShowEditPasswordCategory(true);
  }

  function handleEditPasswordCategoryOk(){
    if(editPasswordCategoryData) {
      // 判断是否新增
      let exist = passwordMetaData?.categorys.find((item) => item.id == editPasswordCategoryData?.id);
      if(exist) {
        passwordMetaData?.categorys.filter((item) => item.id == editPasswordCategoryData?.id)
        .forEach((item) => {
          item.name = editPasswordCategoryData.name;
        });
      } else {
        passwordMetaData?.categorys.splice(0, 0, editPasswordCategoryData);
      }
      setPasswordMetaData(passwordMetaData);
      // 隐藏 modal
      setShowEditPasswordCategory(false);
    } else {
      alert("操作失败")
    }
  }

  function handleEditPasswordCategoryCancel(){
    setShowEditPasswordCategory(false);
  }

  function editPasswordCategoryNameOnChange(e: React.ChangeEvent<HTMLInputElement>) {
    const { value: inputValue } = e.target;
    if(editPasswordCategoryData) {
      setEditPasswordCategoryData({
        id: editPasswordCategoryData?.id,
        name: inputValue,
        datas: editPasswordCategoryData?.datas
      })
    }
  }

  function toggleDeletePasswordCategory(category: PasswordCategory) {
    if(passwordMetaData?.categorys) {
      let datas  = passwordMetaData.categorys.filter((item) => item.id != category.id);
      passwordMetaData.categorys = datas;
      setPasswordMetaData(passwordMetaData);
      if(passwordMetaData.categorys && passwordMetaData.categorys.length > 0) {
        setEditPasswordCategoryData(passwordMetaData.categorys[0]);
      } else {
        setEditPasswordCategoryData({
          id: "" + new Date().getTime(),
          name: "",
          datas: []
        });
      }
    }
  }

  function toggleCreatePasswordItem() {
    setShowEditPasswordItem(false);

    setIsCreatePasswordItem(true);
    setEditPasswordItemData({
      id: "" + new Date().getTime(),
      url: "",
      name: "",
      userName: "",
      password: "",
      encrypt: true
    });
    setShowEditPasswordItem(true);
  }

  function toggleEditPasswordItem(passwordItem: PasswordItem) {
    console.log(JSON.stringify(passwordItem));
    setShowEditPasswordItem(false);

    setIsCreatePasswordItem(false);
    setEditPasswordItemData(passwordItem);
    setShowEditPasswordItem(true);
  }

  function toggleDeletePasswordItem(passwordItem: PasswordItem) {
    if(editPasswordCategoryData?.datas) {
      let datas  = editPasswordCategoryData.datas.filter((item) => item.id != passwordItem.id);
      editPasswordCategoryData.datas = datas;
      setEditPasswordCategoryData(editPasswordCategoryData);

      if(passwordMetaData?.categorys) {
        passwordMetaData?.categorys.filter((item) => item.id == editPasswordCategoryData?.id)
        .forEach((item) => {
          item.datas = editPasswordCategoryData.datas;
        });
        setPasswordMetaData(passwordMetaData);
      }
    }
  }

  function handleEditPasswordItemOk(){
    if(editPasswordItemData) {
      // 判断是否新增
      let exist = passwordCategory?.datas.find((item) => item.id == editPasswordItemData?.id);
      if(exist) {
        passwordCategory?.datas.filter((item) => item.id == editPasswordItemData?.id)
        .forEach((item) => {
          item.id = editPasswordItemData.id;
          item.name = editPasswordItemData.name;
          item.url = editPasswordItemData.url;
          item.userName = editPasswordItemData.userName;
          item.password = editPasswordItemData.password;
          item.encrypt = editPasswordItemData.encrypt;
        });
      } else {
        passwordCategory?.datas.splice(0, 0, editPasswordItemData);
      }
      setPasswordMetaData(passwordMetaData);
      // 隐藏 modal
      setShowEditPasswordItem(false);
    } else {
      alert("操作失败")
    }
  }

  function handleEditPasswordItemCancel(){
    setShowEditPasswordItem(false);
  }

  const onFinish = (values: any) => {
    console.log('Success:', values);
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <div className="HolyGrail">
      <div className="header">
        头部: {passwordMetaData?.appName}
        <Button type="primary" onClick={savePasswordMetaData}>保存配置</Button>
      </div>
      <div className="HolyGrail-body">
        <div className="HolyGrail-category">
          <div className="category-title">密码分类</div>
          <div className="category-add"> 
            <PlusCircleOutlined onClick={()=> toggleCreatePasswordCategory()} />
          </div>
          <div className="password-categorys">
            {
              passwordMetaData?.categorys.map((category) => {
                return <div key={category.id} onClick={() => toggleSelectPasswordCategory(category)} >
                  <span>{category.name}</span>
                  <div className="password-categorys-operation">
                    <EditOutlined className="password-categorys-operation-item"  onClick={() => toggleEditPasswordCategory(category)}/>
                    <DeleteOutlined className="password-categorys-operation-item"  onClick={() => toggleDeletePasswordCategory(category)} />
                  </div>
                </div>
              })
            }
          </div>
        </div>
        <div className="HolyGrail-content">
          <div>
            <span>分组名称:{ passwordCategory?.name }</span>
            <PlusCircleOutlined  className="password-item-add" onClick={()=> toggleCreatePasswordItem()} />
          </div>
          {
            <Table columns={columns} dataSource={passwordCategory?.datas}  size="small" />
          }
        </div>
      </div>

      <Modal title="密码分类" open={showEditPasswordCategory} 
        okText="保存" cancelText="取消"
        onOk={handleEditPasswordCategoryOk} 
        onCancel={handleEditPasswordCategoryCancel}>
          <Input value={editPasswordCategoryData?.name} onChange={editPasswordCategoryNameOnChange}/>
      </Modal>

      <Modal title="密码项" open={showEditPasswordItem} 
        okText="保存" cancelText="取消"
        onOk={handleEditPasswordItemOk} 
        onCancel={handleEditPasswordItemCancel}>
        <Form
          name="basic"
          initialValues={editPasswordItemData}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <div>{JSON.stringify(editPasswordItemData)}</div>
          <Form.Item label="系统" name="name" >
            <Input value={editPasswordItemData?.name} />
          </Form.Item>
          <Form.Item label="URL" name="url" >
            <Input value={editPasswordItemData?.url} />
          </Form.Item>
          <Form.Item label="账号" name="userName" >
            <Input value={editPasswordItemData?.userName} />
          </Form.Item>
          <Form.Item label="密码" name="password" >
          <Input.Password />
          </Form.Item>
          <Form.Item label="是否加密" name="remember" valuePropName="checked">
            <Checkbox></Checkbox>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default App;
